import React, { useRef, useState } from 'react';
import { Animated, Easing, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { px2dp } from '~/utils/px2dp';

const AutoRefreshButton = ({ onRefresh }) => {
    const [isRefreshing, setIsRefreshing] = useState(false);
    const rotateAnim = useRef(new Animated.Value(0)).current;

    const startAnimation = () => {
        setIsRefreshing(true);
        rotateAnim.setValue(0);

        // 启动循环旋转动画
        Animated.loop(
            Animated.timing(rotateAnim, {
                toValue: 1,
                duration: 1000,
                easing: Easing.linear,
                useNativeDriver: true,
            }),
        ).start();

        // 3秒后自动停止
        setTimeout(() => {
            stopAnimation();
        }, 3000);
    };

    const stopAnimation = () => {
        rotateAnim.stopAnimation();
        setIsRefreshing(false);
    };

    const handlePress = () => {
        if (!isRefreshing) {
            startAnimation();
            // 如果有传入的刷新回调函数，执行它
            if (onRefresh) {
                onRefresh();
            }
        }
    };

    const rotation = rotateAnim.interpolate({
        inputRange: [0, 1],
        outputRange: ['0deg', '360deg'],
    });

    return (
        <TouchableOpacity onPress={handlePress} activeOpacity={0.7}>
            <Animated.View style={{ transform: [{ rotate: rotation }] }}>
                <Icon
                    name={isRefreshing ? 'refresh' : 'refresh-outline'}
                    size={px2dp(38)}
                    color={isRefreshing ? '#007AFF' : '#a4a4a4'}
                />
            </Animated.View>
        </TouchableOpacity>
    );
};

export default AutoRefreshButton;
